{% extends "admin/layout.html" %}

{% block title %}{{ asset.name }} - 资产详情 - {{ system_config.site_name|default('项目管理系统') }}{% endblock %}

{% block content %}
    <div class="container-fluid">
        <!-- 页面标题和操作按钮 -->
        <div class="d-flex justify-content-between align-items-center mb-4">
            <div>
                <h1 class="h3 mb-0">{{ asset.name }}</h1>

            </div>
            <div class="btn-group">
                <a href="{{ url_for('asset.asset_form', asset_id=asset.id) }}" class="btn btn-outline-primary">
                    <i class="fas fa-edit me-1"></i> 编辑
                </a>
                <button type="button" class="btn btn-outline-secondary" onclick="changeAssetStatus({{ asset.id }})">
                    <i class="fas fa-sync me-1"></i> 变更状态
                </button>
                <a href="{{ url_for('asset.asset_list') }}" class="btn btn-outline-secondary">
                    <i class="fas fa-arrow-left me-1"></i> 返回
                </a>
            </div>
        </div>

        <div class="row">
            <!-- 基本信息 -->
            <div class="col-lg-8">
                <div class="card mb-4">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">基本信息</h5>
                        <span class="badge
                        {% if asset.status == 'in_use' %}bg-success
                        {% elif asset.status == 'available' %}bg-primary
                        {% elif asset.status == 'maintenance' %}bg-warning
                        {% elif asset.status == 'retired' %}bg-secondary
                        {% else %}bg-light text-dark{% endif %}">
                        {{ asset.status_label }}
                    </span>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="40%">资产编号：</th>
                                        <td><strong>{{ asset.asset_number }}</strong></td>
                                    </tr>
                                    <tr>
                                        <th>资产类别：</th>
                                        <td>{{ asset.category.name if asset.category else '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>序列号：</th>
                                        <td>{{ asset.serial_number or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>型号：</th>
                                        <td>{{ asset.model or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>品牌：</th>
                                        <td>{{ asset.brand or '-' }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="40%">使用人：</th>
                                        <td>
                                            {% if asset.assigned_to %}
                                                {{ asset.assigned_to.name }}
                                            {% else %}
                                                <span class="text-muted">未分配</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>存放位置：</th>
                                        <td>{{ asset.location or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>分配日期：</th>
                                        <td>{{ asset.assigned_date.strftime('%Y-%m-%d') if asset.assigned_date else '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>创建时间：</th>
                                        <td>{{ asset.created_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                    </tr>
                                    <tr>
                                        <th>更新时间：</th>
                                        <td>{{ asset.updated_at.strftime('%Y-%m-%d %H:%M') }}</td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        {% if asset.description %}
                            <div class="mt-3">
                                <label class="form-label fw-bold">资产描述：</label>
                                <p class="mb-0">{{ asset.description }}</p>
                            </div>
                        {% endif %}

                        {% if asset.notes %}
                            <div class="mt-3">
                                <label class="form-label fw-bold">备注：</label>
                                <p class="mb-0 text-muted">{{ asset.notes }}</p>
                            </div>
                        {% endif %}
                    </div>
                </div>

                <!-- 财务信息 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">财务信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-4 text-center">
                                <div class="border rounded p-3">
                                    <div class="text-muted mb-1">购买价格</div>
                                    <div class="h4 text-primary">
                                        {% if asset.purchase_price %}
                                            ¥{{ "%.2f"|format(asset.purchase_price) }}
                                        {% else %}
                                            -
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-center">
                                <div class="border rounded p-3">
                                    <div class="text-muted mb-1">当前价值</div>
                                    <div class="h4 text-success">
                                        {% if asset.current_value %}
                                            ¥{{ "%.2f"|format(asset.current_value) }}
                                        {% else %}
                                            无价值
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-4 text-center">
                                <div class="border rounded p-3">
                                    <div class="text-muted mb-1">年折旧率</div>
                                    <div class="h4 text-info">
                                        {% if asset.depreciation_rate %}
                                            {{ asset.depreciation_rate }}%
                                        {% else %}
                                            -
                                        {% endif %}
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="row mt-4">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="50%">购买日期：</th>
                                        <td>{{ asset.purchase_date.strftime('%Y-%m-%d') if asset.purchase_date else '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>保修月数：</th>
                                        <td>{{ asset.warranty_months or '-' }} 个月</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="50%">保修截止：</th>
                                        <td>
                                            {% if asset.warranty_expiry %}
                                                {{ asset.warranty_expiry.strftime('%Y-%m-%d') }}
                                                {% if asset.warranty_status == 'expiring_soon' %}
                                                    <span class="badge bg-warning ms-1">即将到期</span>
                                                {% elif asset.warranty_status == 'expired' %}
                                                    <span class="badge bg-danger ms-1">已过期</span>
                                                {% endif %}
                                            {% else %}
                                                -
                                            {% endif %}
                                        </td>
                                    </tr>
                                    <tr>
                                        <th>保修状态：</th>
                                        <td>
                                            {% if asset.warranty_status == 'valid' %}
                                                <span class="badge bg-success">有效</span>
                                            {% elif asset.warranty_status == 'expiring_soon' %}
                                                <span class="badge bg-warning">即将到期</span>
                                            {% elif asset.warranty_status == 'expired' %}
                                                <span class="badge bg-danger">已过期</span>
                                            {% else %}
                                                <span class="badge bg-secondary">未知</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- 硬件信息卡片 -->
                <!-- 硬件信息 -->
                <div class="card mb-4">
                    <div class="card-header">
                        <h5 class="card-title mb-0">硬件信息</h5>
                    </div>
                    <div class="card-body">
                        <div class="row">
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="40%">CPU信息：</th>
                                        <td>{{ asset.formatted_cpu or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>内存信息：</th>
                                        <td>{{ asset.formatted_memory  or '-' }}</td>
                                    </tr>

                                    <tr>
                                        <th>磁盘信息：</th>
                                        <td>{{ asset.formatted_disk  or '-' }}</td>
                                    </tr>
                                     <tr>
                                        <th>当前用户名：</th>
                                        <td>{{ asset.formatted_user  or '-' }}</td>
                                    </tr>
                                </table>
                            </div>
                            <div class="col-md-6">
                                <table class="table table-borderless">
                                    <tr>
                                        <th width="40%">操作系统：</th>
                                        <td>{{ asset.formatted_os or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>MAC地址：</th>
                                        <td>{{ asset.formatted_mac  or '-' }}</td>
                                    </tr>
                                    <tr>
                                        <th>IP地址：</th>
                                        <td>{{ asset.formatted_network  or '-' }}</td>
                                    </tr>

                                    <tr>
                                        <th>设备标识：</th>
                                        <td>
                                            {% if asset.host_identifier %}
                                                {{ asset.host_identifier }}
                                                {% if asset.auto_discovered %}
                                                    <span class="badge bg-info ms-1">自动发现</span>
                                                {% endif %}
                                            {% else %}
                                                <span class="text-muted">未绑定</span>
                                            {% endif %}
                                        </td>
                                    </tr>
                                </table>
                            </div>
                        </div>

                        <!-- 设备绑定操作 -->
                        <div class="mt-3 border-top pt-3">
                            <h6 class="fw-bold">设备绑定</h6>
                            {% if asset.host_identifier %}
                                <form method="post" action="{{ url_for('asset.unbind_asset', asset_id=asset.id) }}" class="d-inline">
                                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                    <button type="submit" class="btn btn-outline-warning btn-sm"
                                            onclick="return confirm('确定要解绑设备吗？')">
                                        <i class="fas fa-unlink me-1"></i>解绑设备
                                    </button>
                                </form>
                                <span class="text-muted ms-2">已绑定设备: {{ asset.host_identifier }}</span>
                            {% else %}
                                <form method="post" action="{{ url_for('asset.bind_asset', asset_id=asset.id) }}" class="row g-2 align-items-center">
                                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                                    <div class="col-auto">
                                        <input type="text" name="host_identifier" class="form-control form-control-sm"
                                               placeholder="输入设备标识" required>
                                    </div>
                                    <div class="col-auto">
                                        <button type="submit" class="btn btn-primary btn-sm">
                                            <i class="fas fa-link me-1"></i>绑定设备
                                        </button>
                                    </div>
                                </form>
                            {% endif %}
                        </div>
                    </div>
                </div>
                <!-- 维护记录 -->
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <h5 class="card-title mb-0">维护记录</h5>
                        <button type="button" class="btn btn-sm btn-primary" data-bs-toggle="modal" data-bs-target="#maintenanceModal">
                            <i class="fas fa-plus me-1"></i> 新增维护
                        </button>
                    </div>
                    <div class="card-body">
                        {% if maintenance_logs %}
                            <div class="list-group list-group-flush">
                                {% for log in maintenance_logs %}
                                    <div class="list-group-item">
                                        <div class="d-flex w-100 justify-content-between">
                                            <h6 class="mb-1">{{ log.title }}</h6>
                                            <small class="text-muted">{{ log.maintenance_date.strftime('%Y-%m-%d') }}</small>
                                        </div>
                                        <p class="mb-1">{{ log.description or '无描述' }}</p>
                                        <div class="d-flex justify-content-between align-items-center">
                                            <small class="text-muted">
                                                <i class="fas fa-user me-1"></i>{{ log.performed_by.name if log.performed_by else '未知' }}
                                                {% if log.cost and log.cost > 0 %}
                                                    <i class="fas fa-dollar-sign ms-2 me-1"></i>¥{{ "%.2f"|format(log.cost) }}
                                                {% endif %}
                                                {% if log.duration_hours %}
                                                    <i class="fas fa-clock ms-2 me-1"></i>{{ log.duration_hours }}小时
                                                {% endif %}
                                            </small>
                                            <span class="badge bg-secondary">{{ log.maintenance_type_label }}</span>
                                        </div>
                                        {% if log.next_maintenance_date %}
                                            <small class="text-warning">
                                                <i class="fas fa-calendar-alt me-1"></i>下次维护: {{ log.next_maintenance_date.strftime('%Y-%m-%d') }}
                                            </small>
                                        {% endif %}
                                    </div>
                                {% endfor %}
                            </div>
                        {% else %}
                            <div class="text-center py-4 text-muted">
                                <i class="fas fa-tools fa-2x mb-2"></i>
                                <p>暂无维护记录</p>
                            </div>
                        {% endif %}
                    </div>
                </div>
            </div>

            <!-- 侧边栏信息 -->
            <div class="col-lg-4">
                <!-- 供应商信息 -->
                {% if asset.suppliers %}
                    <div class="card mb-4">
                        <div class="card-header">
                            <h5 class="card-title mb-0">供应商信息</h5>
                        </div>
                        <div class="card-body">
                            {% for supplier in asset.suppliers %}
                                <div class="mb-3 pb-3 {% if not loop.last %}border-bottom{% endif %}">
                                    <h6 class="mb-1">{{ supplier.name }}</h6>
                                    {% if supplier.contact_person %}
                                        <p class="mb-1 small"><i class="fas fa-user me-1"></i>{{ supplier.contact_person }}</p>
                                    {% endif %}
                                    {% if supplier.contact_phone %}
                                        <p class="mb-1 small"><i class="fas fa-phone me-1"></i>{{ supplier.contact_phone }}</p>
                                    {% endif %}
                                    {% if supplier.contact_email %}
                                        <p class="mb-1 small"><i class="fas fa-envelope me-1"></i>{{ supplier.contact_email }}</p>
                                    {% endif %}
                                </div>
                            {% endfor %}
                        </div>
                    </div>
                {% endif %}

                <!-- 快速操作 -->
                <div class="card">
                    <div class="card-header">
                        <h5 class="card-title mb-0">快速操作</h5>
                    </div>
                    <div class="card-body">
                        <div class="d-grid gap-2">
                            <button type="button" class="btn btn-outline-primary" onclick="changeAssetStatus({{ asset.id }}, 'maintenance')">
                                <i class="fas fa-tools me-1"></i> 送修维护
                            </button>
                            <button type="button" class="btn btn-outline-success" onclick="changeAssetStatus({{ asset.id }}, 'available')">
                                <i class="fas fa-check me-1"></i> 标记可用
                            </button>
                            <button type="button" class="btn btn-outline-warning" onclick="changeAssetStatus({{ asset.id }}, 'in_use')">
                                <i class="fas fa-sync me-1"></i> 变更状态
                            </button>
                            <button type="button" class="btn btn-outline-info" onclick="assignAssetToUser({{ asset.id }})">
                                <i class="fas fa-user-plus me-1"></i> 分配人员
                            </button>
                            <button type="button" class="btn btn-outline-danger" onclick="changeAssetStatus({{ asset.id }}, 'retired')">
                                <i class="fas fa-trash me-1"></i> 标记报废
                            </button>
                        </div>
                    </div>
                </div>
            </div>

    <!-- 分配人员模态框 -->
    <div class="modal fade" id="assignModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">分配资产给人员</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="assignForm" method="post">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <input type="hidden" id="assetId" name="asset_id">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="userSelect" class="form-label">选择人员</label>
                            <select class="form-select" id="userSelect" name="user_id" required>
                                <option value="">-- 请选择人员 --</option>
                                {% for member in members %}
                                    <option value="{{ member.id }}">{{ member.name }}</option>
                                {% endfor %}
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="assignDate" class="form-label">分配日期</label>
                            <input type="date" class="form-control" id="assignDate" name="assign_date" required>
                        </div>
                        <div class="mb-3">
                            <label for="assignNotes" class="form-label">分配备注</label>
                            <textarea class="form-control" id="assignNotes" name="notes" rows="3"></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">确认分配</button>
                    </div>
                </form>
            </div>
        </div>
    </div>
        </div>
    </div>

    <!-- 新增维护记录模态框 -->
    <div class="modal fade" id="maintenanceModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">新增维护记录</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="maintenanceForm" method="post">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="maintenance_type" class="form-label">维护类型</label>
                            <select class="form-select" id="maintenance_type" name="maintenance_type" required>
                                <option value="maintenance">日常维护</option>
                                <option value="repair">维修</option>
                                <option value="upgrade">升级</option>
                                <option value="inspection">检查</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="title" class="form-label">维护标题</label>
                            <input type="text" class="form-control" id="title" name="title" required>
                        </div>
                        <div class="mb-3">
                            <label for="description" class="form-label">维护描述</label>
                            <textarea class="form-control" id="description" name="description" rows="3"></textarea>
                        </div>
                        <div class="row">
                            <div class="col-md-4 mb-3">
                                <label for="maintenance_date" class="form-label">维护日期</label>
                                <input type="date" class="form-control" id="maintenance_date" name="maintenance_date"
                                       value=" ">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="next_maintenance_date" class="form-label">下次维护</label>
                                <input type="date" class="form-control" id="next_maintenance_date" name="next_maintenance_date">
                            </div>
                            <div class="col-md-4 mb-3">
                                <label for="performed_by_id" class="form-label">维护人</label>
                                <select class="form-select" id="performed_by_id" name="performed_by_id">
                                    <option value="">-- 选择维护人 --</option>
                                    {% for member in members %}
                                        <option value="{{ member.id }}">{{ member.name }}</option>
                                    {% endfor %}
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6 mb-3">
                                <label for="cost" class="form-label">维护费用</label>
                                <div class="input-group">
                                    <span class="input-group-text">¥</span>
                                    <input type="number" class="form-control" id="cost" name="cost" step="0.01" min="0">
                                </div>
                            </div>
                            <div class="col-md-6 mb-3">
                                <label for="duration_hours" class="form-label">维护时长(小时)</label>
                                <input type="number" class="form-control" id="duration_hours" name="duration_hours" step="0.5" min="0">
                            </div>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" onclick="submitMaintenanceForm()">保存记录</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <!-- 状态变更模态框 -->
    <div class="modal fade" id="statusModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">变更资产状态</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <form id="statusForm" method="post">
                    <input type="hidden" name="csrf_token" value="{{ csrf_token() }}">
                    <div class="modal-body">
                        <div class="mb-3">
                            <label for="newStatus" class="form-label">新状态</label>
                            <select class="form-select" id="newStatus" name="status" required>
                                <option value="available">可用</option>
                                <option value="in_use">使用中</option>
                                <option value="maintenance">维护中</option>
                                <option value="retired">已报废</option>
                                <option value="lost">丢失</option>
                            </select>
                        </div>
                        <div class="mb-3">
                            <label for="statusNotes" class="form-label">备注</label>
                            <textarea class="form-control" id="statusNotes" name="notes" rows="3"
                                      placeholder="请输入状态变更的原因或说明..."></textarea>
                        </div>
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="submit" class="btn btn-primary">确认变更</button>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        function submitMaintenanceForm() {
            const form = document.getElementById('maintenanceForm');
            const formData = new FormData(form);

            // 前端验证
            const title = formData.get('title');
            const maintenanceDate = formData.get('maintenance_date');
            const cost = formData.get('cost');
            const durationHours = formData.get('duration_hours');

            if (!title || !maintenanceDate) {
                alert('请填写维护标题和维护日期');
                return;
            }

            if (!cost && !durationHours) {
                if (!confirm('您没有填写费用和时长，确定要继续提交吗？')) {
                    return;
                }
            }

            fetch("{{ url_for('asset.add_maintenance_log', asset_id=asset.id) }}", {
                method: 'POST',
                body: formData,
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                }
            })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 'success') {
                        // 关闭模态框并刷新页面
                        bootstrap.Modal.getInstance(document.getElementById('maintenanceModal')).hide();
                        location.reload();
                    } else {
                        alert(data.message || '保存失败');
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    alert('请求失败');
                });
        }

        function changeAssetStatus(assetId, defaultStatus = null) {
            if (defaultStatus) {
                document.getElementById('newStatus').value = defaultStatus;
            }

            const form = document.getElementById('statusForm');
            form.action = "{{ url_for('asset.change_asset_status', asset_id=0) }}".replace('0', assetId);

            const modal = new bootstrap.Modal(document.getElementById('statusModal'));
            modal.show();
        }

        function assignAssetToUser(assetId) {
            document.getElementById('assetId').value = assetId;
            document.getElementById('assignDate').valueAsDate = new Date();

            const form = document.getElementById('assignForm');
            form.action = "{{ url_for('asset.assign_asset', asset_id=0) }}".replace('0', assetId);

            const modal = new bootstrap.Modal(document.getElementById('assignModal'));
            modal.show();
        }
    </script>
{% endblock %}